package store

import (
	"codejy/structdef"
	"codejy/utils"
	"fmt"
)

// 注册程类型实例变量
func RegisterInstance(threadStore *structdef.ThreadStore, addr string, varDef map[string]structdef.VarDefinition) {
	//判断变量是否已经注册
	if _, ok := threadStore.InstanceStore[addr]; ok {
		panic("此实例在当前环境中以注册")
	}

	//注册变量
	if _, ok := threadStore.InstanceStore[addr]; !ok {
		threadStore.InstanceStore[addr] = make(map[string]structdef.VarDefinition)
	}
	for k, v := range varDef {
		threadStore.InstanceStore[addr][k] = v
	}
	utils.DebugLog("注册实例后的信息", func() {
		PrintInstance(threadStore)
	})
}

// 判断实例地址是否存在
func IsInstanceExist(threadStore *structdef.ThreadStore, addr string) bool {
	//判断变量是否已经注册
	if _, ok := threadStore.InstanceStore[addr]; ok {
		return true
	}
	return false

}

// 打印实例
func PrintInstance(threadStore *structdef.ThreadStore) {
	for k, v := range threadStore.InstanceStore {
		fmt.Printf("实例地址:%s ,实例属性:%s \n", k, v)
	}
}

// 通过变量名获取实例地址
func GetInstance(threadStore *structdef.ThreadStore, varName string) (string, bool) {
	variable, b := GetVariable(threadStore, varName) //环境变量内保存的实例地址
	if !b {
		return "", false
	}

	return variable.Value, true
}

// 获取全局变量的实例地址
func GetGlobalInstance(threadStore *structdef.ThreadStore, varName string) (string, bool) {
	variable, b := GetGlobalVariable(threadStore, varName) //环境变量内保存的实例地址
	if !b {
		return "", false
	}

	return variable.Value, true
}

// 通过实例地址获取实例属性
func GetInstanceProp(threadStore *structdef.ThreadStore, addr string) (map[string]structdef.VarDefinition, bool) {
	//判断变量是否存在
	if _, ok := threadStore.InstanceStore[addr]; !ok {
		return nil, false
	}
	//通过实例地址获取实例
	typeName := threadStore.InstanceStore[addr] //拿到变量类型
	return typeName, true
}

// 修改实例属性
func SetInstanceProp(threadStore *structdef.ThreadStore, addr string, varDef structdef.VarDefinition) bool {

	//通过实例地址获取实例
	typeName := threadStore.InstanceStore[addr] //拿到变量
	//判断变量是否存在
	if _, ok := typeName[varDef.Name]; !ok {
		return false
	}
	//修改变量
	typeName[varDef.Name] = varDef
	utils.DebugLog("修改实例属性后的信息", func() {
		PrintInstance(threadStore)
	})
	return true

}

// 删除实例
func DeleteInstance(threadStore *structdef.ThreadStore, addr string) bool {
	//判断变量是否存在
	if _, ok := threadStore.InstanceStore[addr]; !ok {
		return false
	}
	//删除变量
	delete(threadStore.InstanceStore, addr)
	utils.DebugLog("删除实例,后的信息", func() {
		PrintInstance(threadStore)
	})
	return true
}

// 获取实例还剩余绑定变量的数量
func GetInstanceVarCount(threadStore *structdef.ThreadStore, addr string) int {
	//判断变量是否存在
	if _, ok := threadStore.InstanceStore[addr]; !ok {
		return 0
	}
	//删除变量
	return len(threadStore.InstanceStore[addr])
}

//实例标记
